"use strict";

function newNormalModal(options) {
    if (options.modalId === undefined || options.modalId === null) {
        alert('未配置modalId!');
        return;
    }
    var normalModal = createModal({
        id: options.id || 'normal_modal',
        modalId: options.modalId,
        type: 'normal',
        showHeader: true,
        modalTitle: options.title,
        modalTitleReplace: options.titleReplace,
        showModalHeaderCloseBtn: true,
        closeFun: options.closeFun,
        showFooter: options.showFooter,
        width: options.width,
        height: options.height,
        hideFun: options.hideFun
    });
    normalModal.attr("ignoreBodyClick", "true");
    var modalNormalBody = $('<div class="modal-normal-body" id="' + options.modalId + '"></div>');
    normalModal.find('.modal-dialog').addClass('modal-dialog-centered');
    var modalBody = normalModal.find('.modal-body');
    modalBody.append(modalNormalBody).css('width', '100%').css('height', '100%').addClass("mb-1 mt-1");
    options.modalId && options.data && pushModalContext(options.modalId, "data", options.data);
    translate(normalModal);
    load(modalNormalBody, options, function(){
        setTimeout(function () {
            modalBody.scroll(function () {
                $('.daterangepicker').each(function () {
                    var $this = $(this);
                    var daterangepicker = $this.data('daterangepicker');
                    if (daterangepicker.isShowing) {
                        daterangepicker.move();
                        var daterangepickerTop = $this.offset().top;
                        daterangepickerTop != 0 && (daterangepickerTop <= modalBody.offset().top || daterangepickerTop >= modalBody.offset().top + modalBody.height()) && daterangepicker.element.blur() && daterangepicker.hide();
                    }
                });
            }).niceScroll({
                railpadding: {
                    top: 0,
                    right: 2,
                    left: 0,
                    bottom: 0
                },
                scrollspeed: 60,
                zindex: 1,
                cursorborderradius: "6px",
                cursorwidth: "6px",
                cursorcolor: "rgba(52, 40, 104, 0.2)",
                cursorborder: "rgba(52, 40, 104, 0.2)",
                oneaxismousemode: false
            });
        }, 500);
        options.loadedFun && options.loadedFun();
        translate(modalNormalBody);
    });
    showModal(normalModal);
    var pageModalIds = page['modalIds'];
    if (!pageModalIds) {
        pageModalIds = [];
        page['modalIds'] = pageModalIds;
    }
    pageModalIds.pushWhenNotExist(options.modalId);
    return normalModal;
}

function newSuccessModal(options) {
    var successModal = createModal({
        id: options.id || 'success_modal',
        type: 'success',
        showHeader: false,
        showFooter: false,
        hideFun: options.hideFun
    });
    var successModalBody = successModal.find('.modal-body');
    successModalBody.append($('<div class="sa-icon sa-success animate" style="display: block;"><span class="sa-line sa-tip animateSuccessTip"></span><span class="sa-line sa-long animateSuccessLong"></span><div class="sa-placeholder"></div><div class="sa-fix"></div></div>'));
    options.title && successModalBody.append($('<div class="section-title mt-2 mb-3"><h2 class="text-gradient-02"><span class="modal-confirm-title translate" translateFor="' + (options.title || '') + '" translateReplace="' + getTranslateReplace(options.titleReplace) + '"></span></h2></div>'));
    successModalBody.append($('<p class="mb-4"><span class="translate lang" translateFor="' + (options.content || '') + '" translateReplace="' + (options.contentReplace || '') + '"></span></p>'));
    successModalBody.append($('<button type="button" class="btn btn-shadow btn-w-3 mb-3" data-dismiss="modal"><span class="translate" translateFor="' + (options.okText || 'btn.ok') + '"></span></button>'));
    options.okFun && successModalBody.find('button').on('click', function(){options.okFun()});
    successModal.find('.modal-dialog').addClass('modal-dialog-centered');
    successModalBody.addClass('text-center');
    translate(successModal);
    showModal(successModal);
    return successModal;
}

function newErrorModal(options) {
    var errorModal = createModal({
        id: options.id || 'error_modal',
        type: 'error',
        showHeader: false,
        showFooter: false,
        hideFun: options.hideFun
    });
    var errorModalBody = errorModal.find('.modal-body');
    errorModalBody.append($('<div class="sa-icon sa-error animate" style="display: block;"><span class="sa-line sa-left animateErrorLeft"></span><span class="sa-line sa-right animateErrorRight"></span><div class="sa-placeholder"></div><div class="sa-fix"></div></div>'));
    options.title && errorModalBody.append($('<div class="section-title mt-2 mb-3"><h2 class="text-gradient-02"><span class="modal-confirm-title translate" translateFor="' + (options.title || '') + '" translateReplace="' + getTranslateReplace(options.titleReplace) + '"></span></h2></div>'));
    errorModalBody.append($('<p class="mb-4"><span class="translate lang" translateFor="' + (options.content || '') + '" translateReplace="' + (options.contentReplace || '') + '"></span></p>'));
    errorModalBody.append($('<button type="button" class="btn btn-shadow btn-w-3 mb-3" data-dismiss="modal"><span class="translate" translateFor="' + (options.okText || 'btn.ok') + '"></span></button>'));
    options.okFun && errorModalBody.find('button').on('click', function(){options.okFun()});
    errorModal.find('.modal-dialog').addClass('modal-dialog-centered');
    errorModalBody.addClass('text-center');
    translate(errorModal);
    showModal(errorModal);
    return errorModal;
}

function newConfirmModal(options) {
    var confirmModal = createModal({
        id: options.id || 'confirm_modal',
        type: 'confirm',
        showHeader: false,
        showFooter: false,
        hideFun: options.hideFun
    });
    var modalConfirmBodyWrapper = $('<div class="modal-confirm-body-wrapper"></div>');
    var modalConfirmBody = $('<div class="modal-confirm-body"><i class="la la-question-circle"></i></div>');
    var modalConfirmTitle = $('<span class="modal-confirm-title translate" translateFor="' + options.title + '" translateReplace="' + getTranslateReplace(options.titleReplace) + '"></span>');
    modalConfirmBody.append(modalConfirmTitle);
    if (options.content != undefined) {
        var modalConfirmContent = $('<div class="modal-confirm-content"><span class="translate" translateFor="' + options.content + '" translateReplace="' + (options.contentReplace || '') + '"></span></div>');
        modalConfirmBody.append(modalConfirmContent);
    }
    var modalConfirmBtn = $('<div class="modal-confirm-btns"></div>');
    var modalConfirmOkBtn = $('<button type="button" class="btn btn-primary btn-shadow" style="width:90px" data-dismiss="modal"><span class="translate" translateFor="' + (options.okText || 'btn.ok') + '"></span></button>');
    modalConfirmOkBtn.on('click', function (e) {
        e.preventDefault();
        options.okFun && options.okFun();
        removeModal(confirmModal);
    });
    var modalConfirmCancelBtn = $('<button type="button" class="btn btn-shadow" style="width:90px;margin-right:20px" data-dismiss="modal"><span class="translate" translateFor="' + (options.cancelText || 'btn.cancel') + '"></span></button>');
    modalConfirmCancelBtn.on('click', function (e) {
        e.preventDefault();
        options.cancelFun && options.cancelFun();
        removeModal(confirmModal);
    });
    confirmModal.find('.modal-dialog');
    confirmModal.find('.modal-body').append(modalConfirmBodyWrapper.append(modalConfirmBody).append(modalConfirmBtn.append(modalConfirmCancelBtn).append(modalConfirmOkBtn)));
    translate(confirmModal);
    showModal(confirmModal);
    return confirmModal;
}

function createModal(options) {
    var id = generateID(options.id);
    var modal = $('<div id="' + id + '" class="modal fade"></div>');
    options.type && modal.addClass('modal-' + options.type);
    var modalContent = $('<div class="modal-content"></div>');
    if (options.showHeader == undefined || options.showHeader == true) {
        var modalHeader = $('<div class="modal-header"></div>');
        options.modalTitle !== undefined && modalHeader.append($('<h4 class="modal-title"><span class="translate" translateFor="' + options.modalTitle + '" translateReplace="' + getTranslateReplace(options.modalTitleReplace) + '"></span></h4>'));
        if (options.showModalHeaderCloseBtn == undefined || options.showModalHeaderCloseBtn == true) {
            var headerCloseBtn = $('<button type="button" class="close" data-dismiss="modal"></button>');
            headerCloseBtn.on('click', function (e) {
                e.preventDefault();
                options.closeFun && options.closeFun();
                removeModal(modal);
            });
            modalHeader.append(headerCloseBtn.append($('<span aria-hidden="true">×</span><span class="sr-only">close</span>')));
        }
        modalContent.append(modalHeader);
    }
    var modalBody = $('<div class="modal-body"></div>');
    modalContent.append(modalBody);
    if (options.showFooter == undefined || options.showFooter == true) {
        var modalFooter = $('<div class="modal-footer"></div>');
        if (options.showFooterSaveBtn == undefined || options.showFooterSaveBtn == true) {
            var saveBtn = $('<button type="button" class="btn btn-primary btn-shadow"><span class="translate" translateFor="' + options.okText + '"></span></button>');
            saveBtn.on('click', function (e) {
                e.preventDefault();
                options.saveFun && options.saveFun();
            });
            modalFooter.append(saveBtn);
        }
        if (options.showFooterCloseBtn == undefined || options.showFooterCloseBtn == true) {
            var closeBtn = $('<button type="button" class="btn btn-shadow" data-dismiss="modal"><span class="translate" translateFor="' + options.cancelText + '"></span></button>');
            closeBtn.on('click', function (e) {
                e.preventDefault();
                options.closeFun && options.closeFun();
                removeModal(modal);
            });
            modalFooter.append(closeBtn);
        }
        modalContent.append(modalFooter);
    }
    var modalDialog = $('<div class="modal-dialog"></div>');
    modal.append(modalDialog.append(modalContent));
    var container = $('#content');
    container.length === 0 && (container = $('body'));
    container.append(modal
        .append($('<button type="button" id="showModalBtn" class="hide" data-toggle="modal" data-target="#' + id + '"></button>'))
        .append($('<button type="button" id="hideModalBtn" class="hide" data-dismiss="modal"></button>')));
    modal.on('show.bs.modal', function () {
        options.showFun && options.showFun();
    }).on('shown.bs.modal', function () {
        textEllipsis(modal, false);
        options.shownFun && options.shownFun();
    }).on('hide.bs.modal', function () {
        if (options.modalId) {
            page['modalIds'] && page['modalIds'].remove(options.modalId);
            clearModalTimeout(options.modalId);
            clearModalTimeoutParam(options.modalId);
        }
        options.hideFun && options.hideFun();
    }).on('hidden.bs.modal', function () {
        options.hiddenFun && options.hiddenFun();
    });
    if (options.type === 'success' || options.type === 'error') {
        modalContent.css('width',  '500px');
    } else if (options.type === 'confirm') {
        modalContent.css('width', options.width || '560px').css('height', options.height || '200px').css('min-height', '200px');
        modalDialog.css('top', '5%');
    } else if (options.type === 'normal') {
        var height = options.height;
        if (!height) {
            height = ($(window).height() - 63) * 0.8 + "px";
        } else {
            modalContent.data('height', options.height);
        }
        modalContent.css('width', options.width || '78%').css('height', height).css('min-height', '300px');
    }
    return modal;
}

function showModal(modal) {
    modal.find('#showModalBtn').click();
}

function hideModal(modal) {
    modal.find('#hideModalBtn').click();
    removeModal(modal);
}

function removeModal(modal) {
    var intervalHandler = setInterval(function () {
        if (!modal.hasClass('show')) {
            modal.remove();
            clearInterval(intervalHandler);
            intervalHandler = null;
        }
    }, 2000);
}
